﻿//Template for your module
//You may wrap it in the closure to add private context
//
// below is the MINIMUM public API of the module
//
// To create a simple test module, paste the code into the init function

//TODO
//
//HISTORY LOG
//
//
//<img src=\"http:\/\/cs11165.vk.com\/uID\/a_7103fe20.jpg\"
//al_profile.php?__query=NAME&al=-1
//
//TODO
(function(){
//do not change "module" var name. This will be the link to the module context (module ~= this)
var module = {
	version : "0.0.6",
	url : "http://vuzzle.googlecode.com/svn/release/usermodules/friendchecker.js",
	updateUrl : "http://vuzzle.googlecode.com/svn/release/usermodules/versions/friendchecker.version",
	name : "friendchecker",
	title : "Друзья",
	description : "Проверяет добавившихся/удалившихся друзей",
	author : "<a href='/konstantin89'>konstantin89</a>",
	depends : [],
	settings : {
		time : {
			text : "Интервал проверки в секундах",
			type : "input:posint",
			value : 300,
			title : "Time to check"
		},
		del : {
			text : "Удалившиеся",
			type : "checkbox",
			value : true,
			title : "Проверять удалившихся друзей"
		},
		add : {
			text : "Добавленные",
			type : "checkbox",
			value : false,
			title : "Проверять добавленных друзей"
		}, 
		id : {
			text : "Список id",
			type : "input:all",
			value : vu.vk.currentUser.id,
			title : "Список id пользователей"
		}
		
		
	},
	onApplySettings : function() {
		//called when user applyes new settings
	},
	onUninstall : function() {

	},
	init : function() {
	///////////////////////////////////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////////////
		function checker(_timer,id,funct,useByTimer){

			var _timerLoad = vu.data.load("timerId_"+id);//получаем сохраненное значение таймера
			var curTime = new Date().getTime();
			var useFunct = funct ? true : false;
			var time = _timerLoad ? _timerLoad : curTime;//берем значение хранилища либо текущее время
			var timer = _timer * 1000;
			
			//текущее время - время хранилища
			//если больше чем время проверки  -  возвращаем true/выполняем функцию
			//если меньше - вешаем функцию на таймаут по оставшемуся времени до проверки/возвращаем время до готовности таймера
			
			if((curTime - time) > timer){
			
				vu.data.save("timerId_"+id,curTime);
				
				if(useFunct){
					funct();
				}else{
					return true;
				};
			
			}else if (useFunct && useByTimer){
			
				setTimeout(function(){
					vu.data.save("timerId_"+id,curTime);
					funct();
				},Math.abs(curTime - time - timer));
				
			}else{
				return Math.abs(curTime - time - timer);
			};

		
		};
		/////////////////////////////////////////////////////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////////////////////////////////////////////////////
		var ids = module.settings.id.value.split(",");

		new vu.ui.Window({
			element: $("<div id='friendcheckerwin'></div>"),
			lable: "Изменения списков",
			idString: "friendchecker"
		});
		
		var $win = $("#friendcheckerwin");

		function getFriends(id){
			vu.xhr.get("friends?act=load_friends_silent&al=1&gid=0&id="+id, null, function(a){
				handling(a,id);
			});
		};
		
		function handling(a,id){
		
			var arr = [];
			var newList = eval("("+a.replace(/\n/gm,'').match(/\[.*\]\]/i)+")");
		
			if(!newList){
				setTimeout(function(){getFriends(id)},500);//??если приходит неправильный ответ попробовать еще раз.
				return
			};
			
			for (var i in newList){
				arr.push(newList[i][0]);
			};
			///////////////////////////////////////////////////////////////////////
			//temporary id:[userName,pageName] cache function
			//console.log(loadName("4518704")); //obj
			//console.log(loadName("4518704")[0]); //pagename 
			//console.log(loadName("4518704")[1]); //username
			///////////////////////////////////////////////////////////////////////

				var _cache = vu.data.load("name_cache");
				if(!_cache || $.isEmptyObject(_cache)){
					_cache = {};
				};
				
				for (var i in newList){
					_cache[newList[i][0]] = newList[i][2]+","+newList[i][4];
				}
				
				vu.data.save("name_cache",_cache);

			///////////////////////////////////////////////////////////////////////
			if(module.settings.add.value){

				changes(arr,true,"add",id);
			};
			
			if(module.settings.del.value){
		
				changes(arr,false,"del",id);
			};
		};
		
		
		
		
			////////////////////////////////////////////////////////////////////////

			function loadName(id){
				var _cache = vu.data.load("name_cache");

				if(!_cache || $.isEmptyObject(_cache) || !_cache[id]){
					return id;
				};
	
				return _cache[id].split(",");
			};
			////////////////////////////////////////////////////////////////////////

		function changes(newList,add,type,id){
		
			var list = vu.data.load("list_"+type+"_"+id);

			if(!list || $.isEmptyObject(list)){
				vu.data.save("list_"+type+"_"+id, newList);
				return
			};
			
			var uids = [];
			var swLength = add ? newList.length : list.length;
			var oldListStr = ","+list.toString()+",";
			var newListStr = ","+newList.toString()+",";
			
			for (var i = 0; i < swLength; i++){
				if(add){

					var re = new RegExp(","+newList[i]+",","");
					
					if(!re.test(oldListStr)){
						uids.push(newList[i]);
					};
					
				}else{

					var re = new RegExp(","+list[i]+",","");
					
					if(!re.test(newListStr)){
						uids.push(list[i]);
					};
				}
				
			};
			
			if(!$.isEmptyObject(uids)){
			
				if(add){
					toWind(id,uids,"blue");
				}else{
					toWind(id,uids,"red");
				};
			};
			
			vu.data.save("list_"+type+"_"+id, newList);
			
		};
		
		function toWind(id,uids,type){

			var obj = "<br>Пользователь : <a href = 'friends?id="+id+"'>"+loadName(id)[1]+"</a>";
			
			if (type == "blue"){
				obj += "<br>Добавилось : " + uids.length;
			}else{
				obj += "<br>Удалилось : " + uids.length; 
			};
			for(var i in uids){
	
				obj += "<br><a href='/id"+uids[i]+"' style='color:"+type+"'>"+loadName(uids[i])[1]+"</a>";
			};
			
			$win.html($win.html()+obj);

			$win.parent().parent().parent().show();
		};
		
		
		var starter = function(){
			if(module.settings.add.value||module.settings.del.value){
				for (var i in ids){
					getFriends(ids[i]);
				};
			};			
		};
		setInterval(function(){
			checker(module.settings.time.value,"friends",starter);
		},1000);
	}
};return module;})();